<template>
  <el-row
    :gutter="10"
    class="mb-0!"
    :class="[
      footer
        ? '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height)-10px)]'
        : '!h-[calc(100vh-var(--top-tool-height)-var(--tags-view-height)-20px)]'
    ]"
  >
    <el-col :xs="24" :sm="12" :md="10" :lg="7" :xl="6">
      <User>
        <template #backButton>
          <el-button
            @click="goReturnUrl('cancel')"
            size="large"
            plain
            type="primary"
            class="w-full custom-text-18 !h-50px"
          >
            返回
          </el-button>
        </template>
      </User>
    </el-col>
    <el-col :xs="24" :sm="12" :md="14" :lg="17" :xl="18">
      <el-row :gutter="10" class="!h-full">
        <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18" class="pos-relative">
          <CartList
            :list="cartList"
            @handle-change-number="onHandleChangeNumber"
            @handle-replace-card="onHandleReplaceCard"
            @handle-change="onHandleChangeNumber"
            @handel-edit="onHandleEdit"
            :rebate-type="state.rebateType"
          >
            <template #tool>
              <ContentWrap class="!w-full border-none!" :body-style="{ padding: 0 }">
                <el-row class="!w-full m-x-0!" justify="space-between">
                  <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                    <div class="flex items-center">
                      <el-text truncated class="custom-text-16">寄存员工</el-text>
                      <el-radio-group
                        :model-value="state.rebateType"
                        class="ml-10px"
                        @change="setReateType"
                      >
                      </el-radio-group>
                      <div class="ml-10px" v-if="state.rebateType == 0">
                        <SystemUserShowcase
                          ref="UserShowcaseRef"
                          v-model:model-value="state.employeeStr"
                          @change="setEmployeeConfirm()"
                          :show-system-users="false"
                          :icon-szie="28"
                        />
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </ContentWrap>
            </template>
          </CartList>
        </el-col>
        <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
          <OrderInfo :cart-employee-text="cartEmployeeText" :order-info="state.orderInfo">
            <template #button>
              <el-button
                type="primary"
                size="large"
                class="w-100% custom-text-18 !h-50px"
                @click="onHandleConfirm"
                >确认订单</el-button
              >
            </template>
          </OrderInfo>
        </el-col>
      </el-row>
    </el-col>
  </el-row>

  <!-- 密码键盘 -->
  <CodeKeyboardDialog @handle-confirm="submitOrder" />

  <!-- 音频 -->
  <audio ref="audioRef" controls v-show="false">
    <source :src="audioUrl" />
  </audio>
</template>

<script lang="ts" setup>
defineOptions({ name: 'ShopPayCashierService' })

import { useTagsViewStore } from '@/store/modules/tagsView'
import User from '@/views/shop/components/member/user/index.vue'
import CartList from './components/CartList.vue'
import OrderInfo from './components/OrderInfo.vue'
import noPaymentAudioUrl from '@/assets/audio/nonPayment.mp3'
import successPaymentAudioUrl from '@/assets/audio/paymentSuccess.mp3'
import successServiceAudioUrl from '@/assets/audio/serveSuccess.mp3'
import CodeKeyboardDialog from '@/views/shop/components/codeKeyboardDialog/index.vue' //密码弹框

const appStore = useAppStore()
const footer = computed(() => appStore.getFooter)
import * as CartApi from '@/api/shop/trade/cart'
import * as OrderApi from '@/api/shop/trade/order'
import * as ConfigApi from '@/api/shop/system/config/index'

import { useTagsView } from '@/hooks/web/useTagsView'
const { closeSelectedTag } = useTagsView()
/** 员工选择 */
import SystemUserShowcase from '@/views/shop/components/system/user/systemUserShowcase.vue'
/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()

const isSetUser = computed(() => {
  return shopUserStore.getIsSetUser
})
import { cloneDeep } from 'lodash-es'

/** 购物车信息 */
import { useShopDepositWithOut } from '@/store/modules/shop/deposit'
const shopDeposit = useShopDepositWithOut()

/** 密码键盘信息 */
import { useShopKeyboardWithOut } from '@/store/modules/shop/keyBoard'
const shopKeyboard = useShopKeyboardWithOut()
/** 服务购物车信息 */
import { useAppStore } from '@/store/modules/app'

const cartList = computed(() => {
  return shopDeposit.getCartList
})

const cartEmployeeText = computed(() => {
  let employeeText = ''
  if (state.rebateType == 0) {
    state.employeeStr.forEach((element: any, index: number) => {
      if (index == state.employeeStr.length - 1) {
        employeeText += element.employeeName + ' ' + element.proportion + '%'
      } else {
        employeeText += element.employeeName + ' ' + element.proportion + '%' + '|'
      }
    })
  } else if (state.rebateType == 1) {
    state.orderInfo.items.forEach((element: any) => {
      element.employeeList &&
        element.employeeList.forEach((ele: any, index: number) => {
          if (index == ele.employeeList.length - 1) {
            employeeText += ele.employeeName + ' ' + ele.proportion + '%'
          } else {
            employeeText += ele.employeeName + ' ' + ele.proportion + '%' + '|'
          }
        })
    })
  }
  return employeeText
})
const orderPayload = computed(() => {
  return shopDeposit.getOrderPayload
})
watch(
  () => orderPayload.value,
  () => {
    Object.assign(state.orderPayload, orderPayload.value)
  }
)

const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { push, currentRoute } = useRouter() // 路由
const { delView } = useTagsViewStore() // 视图操作
const orderId = ref()

const returnUrl = ref<string | undefined>(undefined) // 支付完的回调地址
const state = reactive({
  orderPayload: {} as OrderApi.orderVO,
  orderInfo: {
    items: [] as any, // 商品项列表
    price: {} as any // 价格信息
  },
  showCoupon: false, // 是否展示优惠劵
  couponInfo: [], // 优惠劵列表
  showDiscount: false, // 是否展示营销活动
  // ========== 员工 ==========
  employeeStr: [],

  // ========== 分成 ==========
  rebateType: 0, //0统一 1单一
  // ========== 密码 ==========
  enalePassword: false, // 开启密码支付 true是

  // 补录
  isRepair: false, //是否补录
  repairDate: '', //补录日期
  //支付弹框提示
  paymentTipIcon: 'warning',
  paymentTipTitle: '订单未支付完成,确认提交吗?',
  showPayDialog: false //是否正在支付
})

/** 获得支付信息 */
const getDetail = async () => {
  // 1.1 未传递订单编号
  if (!isSetUser.value) {
    message.error('未选择会员，无法查看对应的购物车信息')
    goReturnUrl('cancel')
    return
  }

  state.orderPayload = orderPayload.value
  state.rebateType = 0
}

/**
 * 回到业务的 URL
 *
 * @param payResult 支付结果
 *                  ① success：支付成功
 *                  ② cancel：取消支付
 *                  ③ close：支付已关闭
 */
const goReturnUrl = (payResult) => {
  // 未配置的情况下，只能关闭
  if (!returnUrl.value) {
    delView(unref(currentRoute))
    return
  }

  const url =
    returnUrl.value.indexOf('?') >= 0
      ? returnUrl.value + '&payResult=' + payResult
      : returnUrl.value + '?payResult=' + payResult
  // 如果有配置，且是 http 开头，则浏览器跳转
  if (returnUrl.value.indexOf('http') === 0) {
    location.href = url
  } else {
    delView(unref(currentRoute))
    push({
      path: url
    })
  }
}

const onHandleChangeNumber = async (item) => {
  const deepCopyFormData = cloneDeep(item) as CartApi.serviceCartItemVO

  await shopDeposit.updateCart(deepCopyFormData)
}
const onHandleEdit = (type, item) => {
  const deepCopyFormData = cloneDeep(item)

  switch (type) {
    case 'setEmployee':
      onHandleSetEmployee(deepCopyFormData)
      break

    default:
      break
  }
}
/**
 * 音频播放
 */
const audioUrl = ref()
const audioRef = ref<any>(null)
const playAudio = (type) => {
  if (type == 'nonPayment') {
    audioRef.value.src = noPaymentAudioUrl
  } else if (type == 'successPayment') {
    audioRef.value.src = successPaymentAudioUrl
  } else if (type == 'successService') {
    audioRef.value.src = successServiceAudioUrl
  }
  console.log(audioUrl.value)
  audioRef.value?.play()
}
/**设置员工 */
const onHandleSetEmployee = async (item) => {
  await shopDeposit.updateCart({
    id: item.id,
    count: item.count,
    employeeStr: item.employeeStr
  })
  message.success('设置成功')
}
// 选择商品
const onHandleReplaceCard = async (item) => {
  console.log(item)
  const deepCopyFormData = cloneDeep(item) as CartApi.serviceCartItemVO

  await shopDeposit.updateCart(deepCopyFormData)
}
/** 切换销售员工类型 */
const setReateType = (type: number) => {
  if (type == 0) {
    state.orderInfo.items.forEach((ele) => {
      ele.employeeList = []
    })
  } //如果是统一销售清除所有商品选择的销售人
  else {
    state.employeeStr = []
  }
  state.rebateType = type
} //切换  销售类型 0 统一 1 单一

/** 选择员工 */
const UserShowcaseRef = ref()
const setEmployeeConfirm = () => {
  if (state.rebateType == 0) {
    if (autoConfirm.value) {
      onHandleConfirm()
    }
  }
}
/** 确认订单 */
const autoConfirm = ref(false) //自动提交
const onHandleConfirm = () => {
  if (cartEmployeeText.value == '') {
    if (state.rebateType == 1) {
      message.error('请选择员工')
    }
    if (state.rebateType == 0) {
      autoConfirm.value = true
      UserShowcaseRef.value.openSpuTableSelect()
    }
    return
  }
  if (state.orderPayload.isRepair) {
    if (state.orderPayload.repairDate == '') {
      message.error('请选择补录日期')
      return
    }
    if (state.orderPayload.remark == '') {
      message.error('请输入补录备注')
      return
    }
  }
  if (state.orderInfo.price.payPrice > 0) {
    return
  }
  confirmOrder()
}
const confirmOrder = async () => {
  // await getEnalePassword()
  // if (state.enalePassword) {
  //   shopDeposit.handleOpenCodeKeyboard()
  //   return
  // }
  submitOrder()
}
const getEnalePassword = async () => {
  let data = await ConfigApi.getSystemConfigByKey('fwEnalePassword')
  state.enalePassword = data.configValue
}
const submitOrder = async () => {
  const items = [] as EmptyArrayType
  state.orderPayload.items.map((item) => {
    items.push({
      skuId: item.skuId,
      skuNumber: item.count,
      cartId: item.cartId
    })
  })
  await OrderApi.createReserveOrder({
    userId: shopUserStore.getUser.id,
    no: orderId.value,
    reserveList: items,
    employeeStr: state.employeeStr, //员工
    type: 1
  })
  ElNotification({
    title: '提示',
    message: '订单完成',
    type: 'success'
  })
  playAudio('successPayment')
  closeSelectedTag()

  // 关闭密码窗口
  shopDeposit.closeCodeKeyBoard()
  // 更新购物车列表，如果来自购物车
}

/** 初始化 */
onMounted(() => {
  if (route.query.returnUrl) {
    returnUrl.value = decodeURIComponent(route.query.returnUrl as string)
  }
  orderId.value = shopDeposit.getOrderId //购物车预订单号

  getDetail()
})
</script>

<style lang="scss" scoped></style>
